<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper"></div>
    <!-- 操作按钮区域 -->

    <!-- table区域-begin -->
    <a-table bordered :columns="columns" :dataSource="dataSource" :pagination="false">
      <template
        v-for="(col, i) in ['portionSet', 'refValue', 'portionRemark']"
        :slot="col"
        slot-scope="text, record, index"
      >
        <a-tooltip title="必填项" :defaultVisible="false" :overlayStyle="{ color: 'red' }">
          <a-input
            :key="col"
            v-if="record.editable"
            style="margin: -5px 0"
            :value="text"
            :placeholder="columns[i].title"
            @change="(e) => handlerRowChange(e.target.value, record.key, col)"
          />
          <template v-else>{{ text }}</template>
        </a-tooltip>
      </template>
      <template slot="operation" slot-scope="text, record, index">
        <template v-if="record.editable">
          <span v-if="record.isNew">
            <a @click="saveRow(record.key)">保存</a>
            <a-divider type="vertical" />
            <a-popconfirm title="是否要删除此行？" @confirm="removeRow2(record.key)"><a>删除</a></a-popconfirm>
          </span>
          <span v-else>
            <a @click="saveRow(record.key)">保存</a>
            <a-divider type="vertical" />
            <a @click="cancelEditRow(record.key)">取消</a>
          </span>
        </template>
        <span v-else>
          <a @click="editRow(record.key)">编辑</a>
          <a-divider type="vertical" />
          <a-popconfirm title="是否要删除此行？" @confirm="removeRow(record.id)"><a>删除</a></a-popconfirm>
        </span>
      </template>
    </a-table>
    <a-button style="width: 100%; margin-top: 16px; margin-bottom: 8px" type="dashed" icon="plus" @click="newRow"
      >新增</a-button
    >
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { getAction, postAction, deleteAction } from '@/api/manage'

export default {
  name: 'UserFormulaPortion',
  components: {},
  data() {
    return {
      description: '算法库管理页面',
      funItems: ['滚动取值', '当日统计', '当月统计', '标准值获取', '日报取值', '日报滚动取值'],
      dataSource: [],
      // 表头
      columns: [
        {
          title: '区间设置',
          dataIndex: 'portionSet',
          key: 'portionSet',
          width: '20%',
          scopedSlots: { customRender: 'portionSet' },
        },
        {
          title: '决策参考值',
          dataIndex: 'refValue',
          key: 'refValue',
          width: '20%',
          scopedSlots: { customRender: 'refValue' },
        },
        {
          title: '处理措施',
          dataIndex: 'portionRemark',
          key: 'portionRemark',
          width: '40%',
          scopedSlots: { customRender: 'portionRemark' },
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      url: {
        list: '/userFormula/userFormula/queryUserFormulaPortionByMainId',
        save: '/userFormula/userFormula/savePortion',
        addPortion: '/userFormula/userFormula/addPortion',
        editPortion: '/userFormula/userFormula/editPortion',
        deletePortion: '/userFormula/userFormula/deletePortion'
      },
      dictOptions: {},
      superFieldList: [],
      loading: false,
    }
  },
  watch: {
    formulaId: {
      handler: function (newVal, oldVal) {
        this.requestData()
      },
    },
  },
  created() {
    if (this.formulaId) {
      this.requestData()
    }
  },
  props: {
    formulaId: {
      type: Number,
    },
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    /** 查询某个tab的数据 */
    requestData() {
      var that = this
      let params = { id: this.formulaId }
      getAction(this.url.list, params)
        .then((res) => {
          let { result } = res
          if (result) {
            if (Array.isArray(result)) {
              result.forEach((element) => {
                element.key = element.id
                element.editable = false
              })
              that.dataSource = result
            } else if (Array.isArray(result.records)) {
              that.dataSource = result.records
            }
          }
        })
        .finally(() => {})
    },
    handlerRowChange(value, key, column) {
      const newData = [...this.dataSource]
      const target = newData.filter((item) => key === item.key)[0]
      if (target) {
        target[column] = value
        this.dataSource = newData
      }
    },
    editRow(key) {
      let target = this.dataSource.filter((item) => item.key === key)[0]
      target.editable = !target.editable
    },
    cancelEditRow(key) {
      let target = this.dataSource.filter((item) => item.key === key)[0]
      target.editable = false
    },
    saveRow(key) {
      var that = this
      let target = this.dataSource.filter((item) => item.key === key)[0]
      target.formulaId = that.formulaId
      //let reg =/^[\d,-./([)\]]+$/
      let reg =/^[\[\(]-?(0|[1-9]\d*|[1-9]\d*\.\d{1,3}|0\.\d{1,3})[,]-?(0|[1-9]\d*|[1-9]\d*\.\d{1,3}|0\.\d{1,3})(\)|])$/
      if(!reg.test(target.portionSet)){
        that.$message.warning("区间设置格式有误");
        return
      } 
      reg =/^(\-|\+)?\d+(\.\d+)?$/
      if(!reg.test(target.refValue)){
        that.$message.warning("决策参考值格式有误");
        return
      }
      
      var url = this.url.addPortion
      if (target.id) {
        url = this.url.editPortion
      }
      postAction(url, target).then((res) => {
        if (res.success) {
          that.$message.success('保存成功')
          target.id = res.result.id
          target.editable = false
          target.isNew = false
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    newRow() {
      // 通过时间戳生成 UUID
      let uuid = Math.round(new Date().getTime()).toString()
      console.log('uuid: ' + uuid)
      this.dataSource.push({
        key: uuid,
        portionSet: '',
        refValue: '',
        portionRemark: '',
        editable: true,
        isNew: true,
      })
    },
    removeRow(id) {
      var that = this
      if (id) {
        deleteAction(that.url.deletePortion, { id: id }).then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            const newData = this.dataSource.filter((item) => item.id !== id)
            that.dataSource = newData
          } else {
            that.$message.warning(res.message)
          }
        })
      }
    },
    removeRow2(key) { 
      this.dataSource = this.dataSource.filter((item) => item.key !== key)
    }
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';

.bsSpan {
  vertical-align: middle;
  display: inline-block;
  width: calc(100% - 0px);
  overflow: hidden;
}
</style>